import React from 'react'
import {Form,Input,Button} from "antd-mobile"
import request from "../../api/request";
import { useCountdown } from '../../hooks/useCountdown';
import { useDispatch } from 'react-redux';
import { loginSuccess } from '../../store/user/userSlice';
import { useNavigate } from 'react-router-dom';

function Login() {
    const navigate=useNavigate();
    const dispatch=useDispatch()
    //封装倒计时
    const {count,getCount,isCount,reset}=useCountdown(5,()=>{
        reset()
    })
    const [form]=Form.useForm();
    const onFinish=(value)=>{
        console.log(value);
    }
    
    //验证码验证
    const getCode=()=>{
        form.validateFields(['tel']).then(async({tel})=>{
            const res=await request.get('/login/code',{
                params:{
                    tel
                }
            })
            console.log(res);
            const telCode=(res.data.data);
            form.setFieldValue('telCode',telCode)
            //跳转首页
            const {code,data,message}=res.data;
            if(code==200){
                alert(message)
                localStorage.setItem('token',res.token)
                dispatch(loginSuccess(data))
                setInterval(()=>{
                    navigate('/')
                },3000)
            }
            else{
                alert(message)
            }
            getCount()
        })
    }
  return (
    <div>
        <div style={{lineHeight:"5vh"}}>
            <h1>绑定手机号</h1>
            <p>未绑定的手机号验证通过后自动完成登录</p>
        </div>
      <Form form={form} onFinish={onFinish} layout='horizontal' footer={
          <Button block type='submit' color='primary' size='large'>
            绑定并登录
          </Button>
        }>
        <Form.Item label='手机号' name='tel' rules={[{ required: true, message: '手机号不能为空' },{pattern:/^1[3-9]\d{9}$/,message:"输入正确的手机号"}]}>
            <Input placeholder='请输入手机号'></Input>
        </Form.Item>

        <Form.Item label='验证码' name='telCode' extra={<Button onClick={()=>getCode()} disabled={isCount}>{isCount ? `${count}秒后重新获取` : '获取验证码'}</Button>}>
            <Input placeholder='请输入验证码'></Input>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Login
